package com.ruoyi.function.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.function.domain.EtcGantryTree;
import com.ruoyi.function.service.IEtcGantryTreeService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * ETC门架区间数据Controller
 * 
 * @author ruoyi
 * @date 2025-09-11
 */
@RestController
@RequestMapping("/function/EtcGantryTree")
public class EtcGantryTreeController extends BaseController
{
    @Autowired
    private IEtcGantryTreeService etcGantryTreeService;

    /**
     * 查询ETC门架区间数据列表
     */
    @PreAuthorize("@ss.hasPermi('function:EtcGantryTree:list')")
    @GetMapping("/list")
    public AjaxResult list(EtcGantryTree etcGantryTree)
    {
        List<EtcGantryTree> list = etcGantryTreeService.selectEtcGantryTreeList(etcGantryTree);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = etcGantryTree.getRoadName() != null && !etcGantryTree.getRoadName().isEmpty() ||
                                   etcGantryTree.getEtcCode() != null && !etcGantryTree.getEtcCode().isEmpty() ||
                                   etcGantryTree.getNodeName() != null && !etcGantryTree.getNodeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<EtcGantryTree> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出ETC门架区间数据列表
     */
    @PreAuthorize("@ss.hasPermi('function:EtcGantryTree:export')")
    @Log(title = "ETC门架区间数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EtcGantryTree etcGantryTree)
    {
        List<EtcGantryTree> list = etcGantryTreeService.selectEtcGantryTreeList(etcGantryTree);
        // 构建树形结构
        List<EtcGantryTree> treeList = buildTree(list);
        // 处理层级数据，将第一层和第二层数据合并到第三层
        List<EtcGantryTree> exportList = new ArrayList<>();
        processTreeData(treeList, exportList);
        ExcelUtil<EtcGantryTree> util = new ExcelUtil<EtcGantryTree>(EtcGantryTree.class);
        util.exportExcel(response, exportList, "ETC门架区间数据数据");
    }

    /**
     * 获取ETC门架区间数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('function:EtcGantryTree:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(etcGantryTreeService.selectEtcGantryTreeById(id));
    }

    /**
     * 新增ETC门架区间数据
     */
    @PreAuthorize("@ss.hasPermi('function:EtcGantryTree:add')")
    @Log(title = "ETC门架区间数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EtcGantryTree etcGantryTree)
    {
        return toAjax(etcGantryTreeService.insertEtcGantryTree(etcGantryTree));
    }

    /**
     * 修改ETC门架区间数据
     */
    @PreAuthorize("@ss.hasPermi('function:EtcGantryTree:edit')")
    @Log(title = "ETC门架区间数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EtcGantryTree etcGantryTree)
    {
        return toAjax(etcGantryTreeService.updateEtcGantryTree(etcGantryTree));
    }

    /**
     * 删除ETC门架区间数据
     */
    @PreAuthorize("@ss.hasPermi('function:EtcGantryTree:remove')")
    @Log(title = "ETC门架区间数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 检查是否可以删除节点（父节点必须在子节点删除完后才能删除）
        for (Long id : ids) {
            if (etcGantryTreeService.hasChildById(id)) {
                return error("节点存在子节点，请先删除子节点后再删除父节点");
            }
        }
        
        return toAjax(etcGantryTreeService.deleteEtcGantryTreeByIds(ids));
    }
    
    /**
     * 构建树形结构
     */
    private List<EtcGantryTree> buildTree(List<EtcGantryTree> list) {
        // 构建父子关系映射
        Map<Long, EtcGantryTree> nodeMap = new HashMap<>();
        List<EtcGantryTree> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (EtcGantryTree node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (EtcGantryTree node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                EtcGantryTree parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<EtcGantryTree>());
                    }
                    @SuppressWarnings("unchecked")
                    List<EtcGantryTree> children = (List<EtcGantryTree>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }
    
    /**
     * 处理层级数据，将第一层和第二层数据合并到第三层
     * 第一层：路段名称 -> 第三层的路段名称
     * 第二层：ETC序号、ETC门架区间、备注 -> 第三层的对应字段
     */
    private void processTreeData(List<EtcGantryTree> treeList, List<EtcGantryTree> exportList) {
        for (EtcGantryTree level1 : treeList) {
            // 第一层数据
            String roadName = level1.getRoadName();
            
            // 处理第二层数据
            if (level1.getChildren() != null && !level1.getChildren().isEmpty()) {
                @SuppressWarnings("unchecked")
                List<EtcGantryTree> level2Children = (List<EtcGantryTree>) level1.getChildren();
                
                for (EtcGantryTree level2 : level2Children) {
                    // 第二层数据
                    String etcCode = level2.getEtcCode();
                    String nodeName = level2.getNodeName();
                    String remark = level2.getRemark();
                    
                    // 处理第三层数据
                    if (level2.getChildren() != null && !level2.getChildren().isEmpty()) {
                        @SuppressWarnings("unchecked")
                        List<EtcGantryTree> level3Children = (List<EtcGantryTree>) level2.getChildren();
                        
                        for (EtcGantryTree level3 : level3Children) {
                            // 将第一层的路段名称设置到第三层
                            level3.setRoadName(roadName);
                            
                            // 将第二层的ETC序号、ETC门架区间、备注设置到第三层
                            if (etcCode != null) {
                                level3.setEtcCode(etcCode);
                            }
                            if (nodeName != null) {
                                level3.setNodeName(nodeName);
                            }
                            if (remark != null) {
                                level3.setRemark(remark);
                            }
                            
                            // 添加到导出列表
                            exportList.add(level3);
                        }
                    }
                }
            }
        }
    }
}
